<template>
  <div class="smart-camera-control">
    <div class="control-header">
      <h2>智能摄像头控制</h2>
      <div class="header-actions">
        <el-button @click="refreshCameraStatus" :loading="loading" type="primary" size="small">
          <el-icon><Refresh /></el-icon>刷新状态
        </el-button>
      </div>
    </div>

    <!-- 摄像头列表 -->
    <div class="cameras-section">
      <div class="cameras-grid">
        <div
          v-for="camera in cameras"
          :key="camera.id"
          class="camera-card"
          :class="{ 'camera-online': camera.online, 'camera-offline': !camera.online }"
        >
          <!-- 摄像头视频流 -->
          <div class="camera-stream" v-if="camera.status === 'on' && camera.streamUrl">
            <video
              :src="camera.streamUrl"
              controls
              muted
              autoplay
              class="stream-video"
              @error="handleStreamError"
            >
              您的浏览器不支持视频播放
            </video>
          </div>

          <!-- 摄像头信息 -->
          <div class="camera-info">
            <h4>{{ camera.name }}</h4>
            <p class="camera-room">{{ camera.room }}</p>
            <div class="camera-status">
              <el-tag :type="camera.online ? 'success' : 'danger'" size="small">
                {{ camera.online ? '在线' : '离线' }}
              </el-tag>
              <el-tag :type="camera.status === 'on' ? 'success' : 'info'" size="small">
                {{ camera.status === 'on' ? '开启' : '关闭' }}
              </el-tag>
              <el-tag v-if="camera.recording" type="warning" size="small">录像中</el-tag>
            </div>
          </div>

          <!-- 摄像头控制面板 -->
          <div class="camera-controls">
            <!-- 开关控制 -->
            <div class="control-group">
              <label>开关控制</label>
              <el-switch
                v-model="camera.status"
                active-value="on"
                inactive-value="off"
                @change="controlCamera(camera.id, 'switch', camera.status === 'on')"
              />
            </div>

            <!-- 录像控制 -->
            <div v-if="camera.status === 'on'" class="control-group">
              <label>录像控制</label>
              <el-button
                :type="camera.recording ? 'danger' : 'success'"
                size="small"
                @click="toggleRecording(camera.id)"
                :loading="recording[camera.id]"
              >
                {{ camera.recording ? '停止录像' : '开始录像' }}
              </el-button>
            </div>

            <!-- 拍照 -->
            <div v-if="camera.status === 'on'" class="control-group">
              <label>拍照</label>
              <el-button
                type="primary"
                size="small"
                @click="takePhoto(camera.id)"
                :loading="takingPhoto[camera.id]"
              >
                <el-icon><Camera /></el-icon>拍照
              </el-button>
            </div>

            <!-- 夜视模式 -->
            <div v-if="camera.status === 'on'" class="control-group">
              <label>夜视模式</label>
              <el-switch
                v-model="camera.nightVision"
                @change="controlCamera(camera.id, 'nightVision', camera.nightVision)"
              />
            </div>

            <!-- 分辨率设置 -->
            <div v-if="camera.status === 'on'" class="control-group">
              <label>分辨率设置</label>
              <el-select v-model="camera.resolution" @change="controlCamera(camera.id, 'resolution', camera.resolution)">
                <el-option label="高清 1080P" value="1080p"></el-option>
                <el-option label="标清 720P" value="720p"></el-option>
                <el-option label="低清 480P" value="480p"></el-option>
              </el-select>
            </div>

            <!-- 角度调节 -->
            <div v-if="camera.status === 'on'" class="control-group">
              <label>角度调节</label>
              <div class="angle-controls">
                <div class="angle-control">
                  <label>水平角度</label>
                  <el-slider
                    v-model="camera.pan"
                    :min="-180"
                    :max="180"
                    :step="5"
                    @change="adjustAngle(camera.id, camera.pan, camera.tilt)"
                    show-input
                    :show-input-controls="false"
                  />
                </div>
                <div class="angle-control">
                  <label>垂直角度</label>
                  <el-slider
                    v-model="camera.tilt"
                    :min="-90"
                    :max="90"
                    :step="5"
                    @change="adjustAngle(camera.id, camera.pan, camera.tilt)"
                    show-input
                    :show-input-controls="false"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 录像列表对话框 -->
    <el-dialog v-model="recordingDialogVisible" title="录像列表" width="800px">
      <div v-if="recordingList.length > 0">
        <el-table :data="recordingList" style="width: 100%">
          <el-table-column prop="fileName" label="文件名" width="200"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
          <el-table-column prop="duration" label="时长" width="100"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="playRecording(scope.row)">播放</el-button>
              <el-button size="small" type="danger" @click="deleteRecording(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalRecordings"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <div v-else class="empty-recordings">
        <el-empty description="暂无录像记录" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { Refresh, Camera } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useDeviceStore } from '../store/deviceStore.js'

export default {
  name: 'SmartCameraControl',
  components: { Refresh, Camera },
  setup() {
    const deviceStore = useDeviceStore()
    const loading = ref(false)
    const recordingDialogVisible = ref(false)
    const recordingList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalRecordings = ref(0)
    const recording = ref({})
    const takingPhoto = ref({})

    // 获取摄像头设备
    const cameras = computed(() => {
      return deviceStore.devices.value.filter(device => device.type === 'camera')
    })

    // 刷新摄像头状态
    const refreshCameraStatus = async () => {
      loading.value = true
      try {
        // 获取所有摄像头的实时状态
        const promises = cameras.value.map(camera =>
          deviceStore.getCameraStatus(camera.id)
        )
        const results = await Promise.allSettled(promises)

        // 更新摄像头状态
        results.forEach((result, index) => {
          if (result.status === 'fulfilled') {
            const camera = cameras.value[index]
            Object.assign(camera, result.value)
          }
        })

        ElMessage.success('摄像头状态刷新完成')
      } catch (error) {
        ElMessage.error('刷新摄像头状态失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 摄像头控制
    const controlCamera = async (deviceId, action, value) => {
      try {
        await deviceStore.controlSmartCamera(deviceId, action, value)
      } catch (error) {
        ElMessage.error('摄像头控制失败：' + error.message)
      }
    }

    // 切换录像状态
    const toggleRecording = async (deviceId) => {
      const camera = cameras.value.find(c => c.id === deviceId)
      if (!camera) return

      recording.value[deviceId] = true
      try {
        const action = camera.recording ? 'stop' : 'start'
        await deviceStore.controlSmartCamera(deviceId, 'recording', action)
        camera.recording = !camera.recording
      } catch (error) {
        ElMessage.error('录像控制失败：' + error.message)
      } finally {
        recording.value[deviceId] = false
      }
    }

    // 拍照
    const takePhoto = async (deviceId) => {
      takingPhoto.value[deviceId] = true
      try {
        const result = await deviceStore.controlSmartCamera(deviceId, 'photo', true)
        ElMessage.success('拍照成功')

        // 可以在这里添加照片预览或下载逻辑
        if (result.photoUrl) {
          // 显示照片预览或提供下载链接
          console.log('照片URL:', result.photoUrl)
        }
      } catch (error) {
        ElMessage.error('拍照失败：' + error.message)
      } finally {
        takingPhoto.value[deviceId] = false
      }
    }

    // 调整角度
    const adjustAngle = async (deviceId, pan, tilt) => {
      try {
        await deviceStore.controlSmartCamera(deviceId, 'angle', null, { pan, tilt })
      } catch (error) {
        ElMessage.error('角度调节失败：' + error.message)
      }
    }

    // 处理视频流错误
    const handleStreamError = (event) => {
      console.error('视频流加载失败:', event)
      ElMessage.warning('视频流加载失败，请检查摄像头连接')
    }

    // 显示录像列表
    const showRecordingList = async (camera) => {
      try {
        const result = await deviceStore.getRecordingList(camera.id, currentPage.value - 1, pageSize.value)
        recordingList.value = result.content || []
        totalRecordings.value = result.totalElements || 0
        recordingDialogVisible.value = true
      } catch (error) {
        ElMessage.error('获取录像列表失败：' + error.message)
      }
    }

    // 播放录像
    // eslint-disable-next-line no-unused-vars
    const playRecording = (_recording) => {
      // 这里可以实现录像播放功能
      ElMessage.info('播放录像功能待实现')
    }

    // 删除录像
    // eslint-disable-next-line no-unused-vars
    const deleteRecording = async (_recording) => {
      try {
        // 这里应该调用删除录像的API
        ElMessage.success('删除录像成功')
        // 刷新录像列表
        showRecordingList(cameras.value[0])
      } catch (error) {
        ElMessage.error('删除录像失败：' + error.message)
      }
    }

    // 分页处理
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      if (recordingDialogVisible.value) {
        showRecordingList(cameras.value[0])
      }
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      if (recordingDialogVisible.value) {
        showRecordingList(cameras.value[0])
      }
    }

    onMounted(() => {
      refreshCameraStatus()
    })

    return {
      cameras,
      loading,
      recordingDialogVisible,
      recordingList,
      currentPage,
      pageSize,
      totalRecordings,
      recording,
      takingPhoto,
      refreshCameraStatus,
      controlCamera,
      toggleRecording,
      takePhoto,
      adjustAngle,
      handleStreamError,
      showRecordingList,
      playRecording,
      deleteRecording,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.smart-camera-control {
  padding: 20px;
}

.control-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cameras-section {
  margin-top: 20px;
}

.cameras-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.camera-card {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.camera-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.camera-card.camera-online {
  border-left: 4px solid #4caf50;
}

.camera-card.camera-offline {
  border-left: 4px solid #f44336;
  opacity: 0.7;
}

.camera-stream {
  height: 200px;
  background: #000;
  position: relative;
  overflow: hidden;
}

.stream-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.camera-info {
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.camera-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.camera-room {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.camera-status {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.camera-controls {
  padding: 15px;
}

.control-group {
  margin-bottom: 15px;
}

.control-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.control-group .el-switch {
  margin-top: 8px;
}

.angle-controls {
  display: flex;
  gap: 15px;
}

.angle-control {
  flex: 1;
}

.angle-control .el-slider {
  margin-top: 8px;
}

.empty-recordings {
  text-align: center;
  padding: 40px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
